﻿#ifndef GLOBALSYMBOL_H
#define GLOBALSYMBOL_H

#include <memory>
#include <functional>

#ifdef WIN32
#include <Windows.h>
#endif // WIN32


#include "GlobalSymbol_global.h"

//用于实现在静态库多重链接下也能保证全局变量唯一的功能,本库只能编译成动态库

typedef void(*SymbolConstructor)(void*);
typedef void(*SymbolDestructor)(void*);

GLOBALSYMBOL_EXPORT void*   GetOrCreateSymbol(const char* SymbolName, int size, SymbolConstructor cons, SymbolDestructor des);
GLOBALSYMBOL_EXPORT void  ReleaseSymbol(const char* SymbolName);

template<typename T>
auto GetOrAcquireSymbol(const char* name) ->std::unique_ptr<T, std::function<void(T*)>>{
	SymbolConstructor cons = [](void* v) {
		new (v)T();
	};

	SymbolDestructor des = [](void* v) {
		auto t = static_cast<T*>(v);
		t->~T();
	};

	void* t = GetOrCreateSymbol(name, sizeof(T),cons,des);

    std::function<void(T*)> deleter = [=](T* t) {
		ReleaseSymbol(name);
	};

    std::unique_ptr<T, std::function<void(T*)>> ret((T*)t, deleter);

	return ret;
}

#define GLOBAL_SYMBOL_ACQUIRE(type,name) GetOrAcquireSymbol<type>(#name);

#endif // !GLOBALSYMBOL_H
